package cn.agiledata.bank.common.tag;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.jsp.JspException;

import org.apache.struts.taglib.TagUtils;
import org.apache.struts.taglib.html.Constants;
import org.apache.struts.taglib.html.OptionsTag;
import org.apache.struts.taglib.html.SelectTag;

import cn.agiledata.bank.common.servlet.InitForString;

public class AgileOptionsTag extends OptionsTag {

	private boolean dummy = true;
	private boolean readonly = false;

	private String dummyLabel = "";

	private String typeid;

	public boolean isDummy() {
		return dummy;
	}

	public void setDummy(boolean dummy) {
		this.dummy = dummy;
	}

	public String getDummyLabel() {
		return dummyLabel;
	}

	public void setDummyLabel(String dummyLabel) {
		this.dummyLabel = dummyLabel;
	}

	public String getTypeid() {
		return typeid;
	}

	public void setTypeid(String typeid) {
		this.typeid = typeid;
	}
	
	public boolean isReadonly() {
		return readonly;
	}

	public void setReadonly(boolean readonly) {
		this.readonly = readonly;
	}

	public int doEndTag() throws JspException {

		// Acquire the select tag we are associated with
		SelectTag selectTag = (SelectTag) pageContext
				.getAttribute(Constants.SELECT_KEY);
		if (selectTag == null) {
			throw new JspException(messages.getMessage("optionsTag.select"));
		}
		StringBuffer sb = new StringBuffer();

		Iterator valuesIterator = null;
		valuesIterator = getIdIterator(typeid);

		Iterator labelsIterator = null;
		labelsIterator = getNameIterator(typeid);

		// Render the options tags for each element of the values coll.
		while (valuesIterator != null && valuesIterator.hasNext()) {
			Object valueObject = valuesIterator.next();
			if (valueObject == null) {
				valueObject = "";
			}
			String value = valueObject.toString();
			String label = value;
			if ((labelsIterator != null) && labelsIterator.hasNext()) {
				Object labelObject = labelsIterator.next();
				if (labelObject == null) {
					labelObject = "";
				}
				label = labelObject.toString();
			}
			if(!isReadonly())
			addOption(sb, value, label, selectTag.isMatched(value));
			else if(selectTag.isMatched(value))
			addOption(sb, value, label, true);
		}

		TagUtils.getInstance().write(pageContext, sb.toString());

		return EVAL_PAGE;

	}
//flag true 
	protected Iterator getIdIterator(String typeid)
			{

		List list = new ArrayList();
		if(dummy)list.add("");
		List u=InitForString.getListId(typeid);
		if(u!=null){
			list.addAll(u); 
		}
		return list.iterator();

	}
	protected Iterator getNameIterator(String typeid)
	{	
		List list = new ArrayList();
		if(dummy)list.add(dummyLabel);
		List u=InitForString.getListName(typeid);
		if(u!=null){
			list.addAll(u); 
		}
		return list.iterator();
	}



}
